﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using System;
using System.Threading.Tasks;
using ItemComponent;

namespace Item
{
    public static class ItemFactory 
    {
        public static async Task<ItemBase> CreateItem(string itemTag)
        {
            STItemData? itemData = ItemDataMgr.Ins[itemTag];
            ItemBase item = null;

            if (itemData.HasValue)
            {
                STItemData data = itemData.Value;

                //TODO 看有没有必要初始化全部加载一遍
                //加载预制
                GameObject prefab = await Addressables.LoadAssetAsync<GameObject>(data.strPrefabPath).Task;
                if (prefab == null)
                    throw new Exception($"加载预制失败 --- Tag:{itemTag} Path:{data.strPrefabPath}");

                GameObject obj = MonoBehaviour.Instantiate(prefab);
                item = obj.GetComponent<ItemBase>();
                if (item != null)
                {
                    //预制上已经挂脚本了
                }
                else
                {
                    //需要手动添加脚本
                    Type type = Type.GetType(data.strTypeName);
                    if (type == null)
                        throw new Exception($"找不到指定的类型 --- Tag:{itemTag} Type:{data.strTypeName}");
                    if (!typeof(ItemBase).IsAssignableFrom(type))
                        throw new Exception($"指定的类型没有继承 ItemBase 类 --- Tag:{itemTag} Type:{data.strTypeName}");

                    item = (ItemBase)obj.AddComponent(type);
                    if (item == null)
                        throw new Exception($"添加组件失败 --- Tag:{itemTag} Type:{type.FullName}");
                }
            }
            else
            {
                //TOPO 去 ILRuntime 里面创建
                Debug.LogError($"未找到道具信息  Tag:{itemTag}");
            }

            if (item != null)
            {
                item.ItemTag = itemTag;
                item.gameObject.name = itemTag;

                try
                {
                    for (int i = 0; i < itemData?.arrMyComponetDatas.Length; i++)
                    {
                        item.AddMyComponent(itemData.Value.arrMyComponetDatas[i]);
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            else
            {
                Debug.LogError($"道具创建失败  Tag:{itemTag}");
            }
            return item;
        }
    }
}